/*
  Losu Copyright Notice
  --------------------
    Losu is an open source programming language project under the MIT license
  that can be used for both academic and commercial purposes. There are no
  fees, no royalties, and no GNU-like restrictions. Losu qualifies
  as open source software. However, Losu is not public property, and founder
  'chen-chaochen' retains its copyright.

    Losu has been registered with the National Copyright Administration of the
  People's Republic of China, and adopts the MIT license as the copyright
  licensing contract under which the right holder conditionally licenses its
  reproduction, distribution, and modification rights to an unspecified public.

    If you use Losu, please follow the public MIT agreement or choose to enter
  into a dedicated license agreement with us.

  The MIT LICENSE is as follows
  --------------------
  Copyright  2020  chen-chaochen

    Permission is hereby granted, free of charge, to any person obtaining a
  copy of this software and associated documentation files (the “Software”), to
  deal in the Software without restriction, including without limitation the
  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  sell copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
*/

#ifndef FILE_SRC_CORE_TASK_C
#define FILE_SRC_CORE_TASK_C

#include "losu.h"
#include "losu_bytecode.h"
#include "losu_dump.h"
#include "losu_gc.h"
#include "losu_mem.h"
#include "losu_object.h"
#include "losu_syntax.h"
#include "losu_vm.h"

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

/**
 * @brief call back a losu-thread yield
 * @param vm vm
 * @param task task struct
 * @return 0 is ok, 1 is error
 */
losu_extern_t losu_ctype_bool losu_vmtask_yield(losu_vm_t vm,
                                                losu_vmtask_t task) {
  if (!vm->yield)
    return 1;
  vm->taskcb = task;
  losu_sigmsg_throw(vm, losu_signal_yield);
  return 0;
}

void __losu_vmtask_mainloop(losu_vm_t vm) {
  losu_ctype_bool hasActive = 1;
  while (hasActive) {
    hasActive = 0;
    for (losu_object_coroutine_t coro = vm->coropool; coro; coro = coro->next) {
      // check coro is awaited?
      if (coro->awaited) {
        hasActive = 1;
        switch (coro->awaited) {
          case losu_vmtask_type_cancel: {
            for (losu_object_t it = coro->top - 1; it != coro->stack; it--) {
              if (ovtype(it) == losu_object_type_context) {
                int32_t nres = ovcontext(it)->nres;
                if (nres == -1)
                  nres = 1;
                for (int i = 0; i < nres; i++)
                  *(it + i) = __losu_objconst_false;
                *it = __losu_objconst_true;
                coro->top = it + nres;
                break;
              }
            }
            break;
          }
          case losu_vmtask_type_await: {  // wait a coro
            losu_object_coroutine_t lock = coro->await.coro;
            if (lock->sta != losu_objcoro_stateEND)
              continue;
            // return true, backvalue
            for (losu_object_t it = coro->top - 1; it != coro->stack; it--) {
              if (ovtype(it) == losu_object_type_context) {
                int32_t nres = ovcontext(it)->nres;
                if (nres == -1)
                  nres = 1;
                for (int i = 0; i < nres; i++)
                  *(it + i) = __losu_objconst_false;
                // *it = *(lock->top - 1);
                // *(it + 1) = *(lock->top - 1);
                *it = obj_newunit(vm, obj_unittype_unit);
                obj_unitsetstr(vm, *it, "data", *(lock->top - 1));
                coro->top = it + nres;
                break;
              }
            }
            break;
          }
          case losu_vmtask_type_sleep: {  // sleep ticks
            clock_t t0 = coro->await.tick;
            if (clock() < t0)
              continue;
            for (losu_object_t it = coro->top - 1; it != coro->stack; it--) {
              if (ovtype(it) == losu_object_type_context) {
                int32_t nres = ovcontext(it)->nres;
                if (nres == -1)
                  nres = 1;
                for (int i = 0; i < nres; i++)
                  *(it + i) = __losu_objconst_false;
                *it = __losu_objconst_true;
                coro->top = it + nres;
                break;
              }
            }
            break;
          }
          case losu_vmtask_type_systhread: {
            losu_vmtask_syscb_t cb = coro->await.syscb;
            if (cb->state == 0)
              continue;
            for (losu_object_t it = coro->top - 1; it != coro->stack; it--) {
              if (ovtype(it) == losu_object_type_context) {
                int32_t nres = ovcontext(it)->nres;
                if (nres == -1)
                  nres = 1;
                for (int i = 0; i < nres; i++)
                  *(it + i) = __losu_objconst_false;
                switch (cb->datatype) {
                  case losu_vmtask_syscb_type_false: {
                    *it = __losu_objconst_false;
                    break;
                  }
                  case losu_vmtask_syscb_type_true: {
                    *it = __losu_objconst_true;
                    break;
                  }
                  case losu_vmtask_syscb_type_number: {
                    *it = obj_newnum(vm, *(losu_ctype_number*)cb->data);
                    break;
                  }
                  case losu_vmtask_syscb_type_string: {
                    *it = obj_newstrlen(vm, (const char*)cb->data, cb->datalen);
                    break;
                  }
                  case losu_vmtask_syscb_type_numarray: {
                    *it = obj_newunit(vm, obj_unittype_array);
                    for (size_t i = 0; i < cb->datalen; i++) {
                      obj_unitsetnum(
                          vm, *it, i,
                          obj_newnum(vm, *((losu_ctype_number*)cb->data + i)));
                    }
                    break;
                  }
                  case losu_vmtask_syscb_type_strarray: {
                    *it = obj_newunit(vm, obj_unittype_array);
                    for (size_t i = 0; i < cb->datalen; i++) {
                      obj_unitsetnum(
                          vm, *it, i,
                          obj_newstr(vm, *((const char**)cb->data + i)));
                    }
                    break;
                  }
                  case losu_vmtask_syscb_type_pointer: {
                    *it = obj_newptr(vm, cb->data);
                    break;
                  }
                  default: {
                    *it = __losu_objconst_false;
                    break;
                  }
                }

                // *(it) = cb->data;
                coro->top = it + nres;
                if (cb->malloced)
                  losu_mem_free(vm, cb->data);
                losu_mem_free(vm, cb);

                break;
              }
            }
            break;
          }
          default:
            break;
        }
        coro->awaited = losu_vmtask_type_none;
      }
      // run a coro
      int32_t sta = vm_await(vm, coro);
      switch (sta) {
        case losu_signal_yield: {  // yield a coro
          hasActive = 1;
          if (vm->taskcb.type) {
            // add callback
            coro->awaited = vm->taskcb.type;
            switch (vm->taskcb.type) {
              case losu_vmtask_type_cancel: {  // cancel a coro
                losu_object_coroutine_t cancel = vm->taskcb.value.coro;
                cancel->sta = losu_objcoro_stateEND;
                *(cancel->stack) = __losu_objconst_false;
                cancel->top = cancel->stack + 1;
                break;
              }
              case losu_vmtask_type_await: {
                coro->await.coro = vm->taskcb.value.coro;
                break;
              }
              case losu_vmtask_type_sleep: {
                coro->await.tick = vm->taskcb.value.tick;
                break;
              }
              case losu_vmtask_type_systhread: {
                // need OS thread library, such as POSIX thread
                coro->await.syscb = vm->taskcb.value.syscb;
                break;
              }
              default:
                break;
            }
            vm->taskcb.type = losu_vmtask_type_none;
          }
          break;
        }
        case losu_signal_done:
        case losu_signal_error: {
          hasActive = 1;
          break;
        }
        default: {
          break;
        }
      }
    }
  }
}

#endif